
package com.netease.xone.fragment;

import java.util.List;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.AppInfo;
import protocol.meta.TopicVO;
import protocol.meta.User;
import protocol.transactions.TransactionGetAtDiscussList;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityFindFriends;
import com.netease.xone.activity.ActivitySquareDiscuss;
import com.netease.xone.activity.ActivityTopicInfoList;
import com.netease.xone.adapter.AdapterInfo.ViewTag;
import com.netease.xone.itemview.RenderInfoBase;
import com.netease.xone.widget.LoadingImageView;

import db.manager.ManagerAppInfo;

public class FragmentSquare extends FragmentBase implements IFragmentMain {

    public static FragmentSquare newInstance() {
        FragmentSquare fragment = new FragmentSquare();
        return fragment;
    }

    // ---找朋友View的尺寸参数---
    private static final float IMAGE_PADDING_DP = 1.66f;
    // ---找朋友View的尺寸参数---

    // View
    private LoadingImageView[] mFindFriendsImageViews;
    private LinearLayout mTopicContainer;
    private LinearLayout mPopDiscussContainer;
    // View size
    private int mFindFriendsViewPadding;
    private int mImageSize;
    // Tid
    private int mFindFriendsTid;
    private int mTopicTid;
    private int mPopDiscussTid;
    // Data
    private int mFindFriendsViewCount;
    private int mTopicCount = 5;

    private List<User> mPopUsers;
    private List<TopicVO> mTopics;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFindFriendsViewCount = getResources().getInteger(
                R.integer.pgsquare_find_friends_view_count);
        mFindFriendsImageViews = new LoadingImageView[mFindFriendsViewCount];
        computeImageSize();
    }

    /**
     * 计算找朋友图片的宽高, 充满屏幕宽度
     */
    private void computeImageSize() {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        float density = getResources().getDisplayMetrics().density;
        mFindFriendsViewPadding = Math.round(IMAGE_PADDING_DP * density);
        mImageSize = (screenWidth - mFindFriendsViewPadding * (mFindFriendsViewCount * 2 + 2))
                / mFindFriendsViewCount;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.fragment_square, null);
        // clickable title
        TextView findFriendClick = (TextView)view.findViewById(R.id.square_find_friend_click);
        TextView hotDiscussClick = (TextView)view.findViewById(R.id.square_hot_discuss_click);
        TextView hotTopicClick = (TextView)view.findViewById(R.id.square_hot_topic_click);
        findFriendClick.setOnClickListener(mClick);
        hotDiscussClick.setOnClickListener(mClick);
        hotTopicClick.setOnClickListener(mClick);

        mPopDiscussContainer = (LinearLayout)view.findViewById(R.id.square_hot_discuss_container);
        mTopicContainer = (LinearLayout)view.findViewById(R.id.square_hot_topic_container);
        LinearLayout findFriendsContainer = (LinearLayout)view
                .findViewById(R.id.square_find_friends_container);
        findFriendsContainer.setPadding(mFindFriendsViewPadding, 0, mFindFriendsViewPadding, 0);
        float density = getResources().getDisplayMetrics().density;
        for (int i = 0; i < mFindFriendsViewCount; i++) {
            mFindFriendsImageViews[i] = new LoadingImageView(getActivity());
            mFindFriendsImageViews[i].setPadding((int)(IMAGE_PADDING_DP * density), 0,
                    (int)(IMAGE_PADDING_DP * density), 0);
            LayoutParams para = new LayoutParams(mImageSize, mImageSize, 1);
            findFriendsContainer.addView(mFindFriendsImageViews[i], para);
            mFindFriendsImageViews[i].setScaleType(ScaleType.FIT_XY);
            mFindFriendsImageViews[i].setImageResource(R.drawable.avatar_user_default_110);
            mFindFriendsImageViews[i].setServerClipSize(mImageSize, mImageSize);
            mFindFriendsImageViews[i].setTag(i);
            mFindFriendsImageViews[i].setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int index = (Integer)v.getTag();
                    if (mPopUsers != null && index < mPopUsers.size()) {
                        User u = mPopUsers.get(index);
                        Toast.makeText(getActivity(),
                                "user:" + u.nickname + ", avatar:" + u.avatar, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
        }
        XoneService.getInstance().addListener(mCallBack);
        mFindFriendsTid = XoneService.getInstance().doGetPopFriendList(1, mFindFriendsViewCount);
        mTopicTid = XoneService.getInstance().doGetTopicList(mTopicCount);
        mPopDiscussTid = XoneService.getInstance().doGetPopDiscussList(1, 1);
        return view;
    }

    @Override
    public void onDestroy() {
        XoneService.getInstance().removeListener(mCallBack);
        super.onDestroy();
    };

    private OnClickListener mClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.square_find_friend_click) {
                ActivityFindFriends.startActivity(getActivity());
            } else if (v.getId() == R.id.square_hot_discuss_click) {
                ActivitySquareDiscuss.startActivity(getActivity());
            } else if (v.getId() == R.id.square_hot_topic_click) {
//                XoneService.getInstance().doGetCommentDiscussList(XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT, -1, -1);
                XoneService.getInstance().doGetAtDiscussList(TransactionGetAtDiscussList.TYPE_DISCUSS, 25, -1, -1);
                XoneService.getInstance().doGetAtDiscussList(TransactionGetAtDiscussList.TYPE_COMMENT, 25, -1, -1);
                XoneService.getInstance().doGetPraiseDiscussList(true, 25, -1, -1);
            }
        }
    };

    XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetPopFriendsList(int transactionId,
                java.util.List<protocol.meta.User> userList) {
            if (mFindFriendsTid == transactionId) {
                mPopUsers = userList;
                int count = userList.size() < mFindFriendsViewCount ? userList.size()
                        : mFindFriendsViewCount;
                for (int i = 0; i < count; i++) {
                    User user = userList.get(i);
                    if (!TextUtils.isEmpty(user.avatar)) {
                        mFindFriendsImageViews[i].setLoadingImage(user.avatar);
                    }
                }
            }
        };

        @Override
        public void onGetTopicList(int transactionId,
                java.util.List<protocol.meta.TopicVO> topicList) {
            if (mTopicTid == transactionId) {
                mTopics = topicList;
                int count = topicList.size() < mTopicCount ? topicList.size()
                        : mFindFriendsViewCount;
                mTopicContainer.removeAllViews();
                for (int i = 0; i < count; i++) {
                    final TopicVO topic = topicList.get(i);
                    View topicItem = View
                            .inflate(getActivity(), R.layout.view_hot_topic_item, null);
                    topicItem.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            ActivityTopicInfoList.startActivity(getActivity(), topic.topicId, topic.topicName);
                        }
                    });
                    TextView topicName = (TextView)topicItem.findViewById(R.id.topic_name);
                    TextView topicPaticipateCount = (TextView)topicItem
                            .findViewById(R.id.topic_participate_count);
                    mTopicContainer.addView(topicItem);
                    topicName.setText("#" + topic.topicName + "#");
                    topicPaticipateCount.setText(String.valueOf(topic.num));
                }
            }
        };

        @Override
        public void onGetPopDiscussList(int transactionId) {
            if(mPopDiscussTid == transactionId){
                Cursor c = ManagerAppInfo.getCursorByGroup(ManagerAppInfo.GROUP_POP_DISCUSS_LIST);
                if(c != null && c.moveToFirst()){
                    mPopDiscussContainer.removeAllViews();
                    String value = c.getString(ManagerAppInfo.JSON);
                    AppInfo appInfo;
                    Gson gson = new Gson();
                    appInfo = gson.fromJson(value, AppInfo.class);
                    View view = View.inflate(getActivity(), R.layout.item_view_info_base, null);
                    RenderInfoBase base = new RenderInfoBase(view);
                    base.renderView(getActivity(), appInfo);
                    mPopDiscussContainer.addView(view);
                }
                if(c != null)c.close();
            }
        };
    };

    @Override
    public void onPageSelected(int index) {
        getActivity().setTitle(R.string.main_tab_plaza);
    }

    @Override
    public void onPageReSelected(int index) {

    }

}
